import { createRouter, createWebHistory } from "vue-router";
import Home from "@/views/index.vue";
import UserCenter from "@/views/userCenter/index.vue";
import CreateCenter from "@/views/createCenter/index.vue";
import Login from "@/views/login/index.vue";
import { useUserStore } from "@/store/userStore";
import { useLoginModalStore } from "@/store/loginModalStore";
import Video from "@/views/video/index.vue";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import UserHome from "@/views/user/index.vue";

// 设置 NProgress 配置
NProgress.configure({ showSpinner: false });

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: "/", component: Home },
    { path: "/login", component: Login },
    { path: "/user", component: UserCenter },
    { path: "/create", component: CreateCenter },
    { path: "/video/:videoId", component: Video },
    { path: "/:userId", component: UserHome },
  ],
});

router.beforeEach(async (to, from) => {
  const userStore = useUserStore(); // 获取用户状态管理
  const loginModalStore = useLoginModalStore(); // 获取登录弹窗管理

  // 开始 NProgress
  NProgress.start();

  try {
    // 尝试获取用户信息，检查是否登录
    if (!userStore.isLogin) {
      throw new Error("User not logged in");
    }
    await userStore.getInfo();
    return true; // 如果获取成功，放行
  } catch (error) {
    // 如果获取失败（例如 token 失效），则清除登录状态并显示登录弹窗
    userStore.logout();

    // 如果当前路径是首页，并且是首次加载，允许页面显示（避免死循环）
    if (to.path === "/" && !from.name) {
      return true;
    }

    loginModalStore.visible = true;

    // 如果是其他页面，跳转到首页
    return "/";
  }
});

router.afterEach(() => {
  // 页面加载完成后，停止 NProgress
  NProgress.done();
});

export default router;
